<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <r-table
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :isHandle="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :tableHandles="tableHandles"
      @refresh="init()"
    >
    </r-table>

    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules"
      :formCols="formCols"
      :formHandle="formHandle"
      :formData="formData"
      ref="elForm"
      :inline="false"
      dialogWidth="850px"
    >
      <!-- 点击Edit按钮出现的Template，里面的站点地址 -->
      <!-- 省 -->
      <div class="zhandiandiz" v-if="isshowss">
        <span>省/市/区/街</span>
        <el-select
          v-model="sValue"
          placeholder="Please Select省份"
          @change="sZhandiandizhi($event)"
          class="szddz"
        >
          <el-option
            v-for="item in sOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 市 -->
        <el-select
          v-model="cValue"
          placeholder="Please Select城市"
          @change="cZhandiandizhi($event)"
          class="czddz"
        >
          <el-option
            v-for="item in cOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 区 -->
        <el-select
          v-model="qValue"
          placeholder="Please Select区/县"
          @change="qZhandiandizhi($event)"
          class="qzddz"
        >
          <el-option
            v-for="(item, index) in qOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 街 -->
        <el-select
          v-model="jValue"
          placeholder="Please Select街道"
          @change="jZhandiandizhi($event)"
          class="jzddz"
        >
          <el-option
            v-for="(item, index) in jOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>

      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"
        ></div>
        <!-- <p>点击地图拾取坐标 经度：{{formData.lng}} 纬度：{{formData.lat}}</p> -->
        <div id="l-map"></div>
      </div>
    </r-form>

    <!--    <r-form :formRules="formRulesEditPsw" :formHandle="formHandleEditPsw" :formData="formDataEditPsw" :formCols="formColsEditPsw" ref="elFormEditPsw" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />-->
    <!--    <r-form :formRules="formRulesActive" :formHandle="formHandleActive" :formData="formDataActive" :formCols="formColsActive" ref="elFormActive" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />-->
  </div>
</template>

<script>
import baidumap from "../js/baidumap";
export default {
  data() {
    var checkpass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Enter Again PassWord"));
      } else if (value !== this.formData.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    var checkpass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Enter Again PassWord"));
      } else if (value !== this.formDataEditPsw.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    return {
      pt: "116.331398, 39.897445",
      isshowss: false, //Control省市区街显示隐藏
      sValue: "", //Edit页面 站点地址 选项的值(省)
      sLabel: "", //Edit页面 站点地址 选项的键名(省)
      sJingwei: "", //Edit页面 站点地址 选项的经纬度(省)
      sOption: [], //Edit页面 站点地址 Data源(省)
      cValue: "", //Edit页面 站点地址 选项的值(市)
      cLabel: "", //Edit页面 站点地址 选项的键名(市)
      cJingwei: "", //Edit页面 站点地址 选项的经纬度(市)
      cOption: [], //Edit页面 站点地址 Data源(市)
      qValue: "", //Edit页面 站点地址 选项的值(区)
      qLabel: "", //Edit页面 站点地址 选项的键名(区)
      qJingwei: "", //Edit页面 站点地址 选项的经纬度(区)
      qOption: [], //Edit页面 站点地址 Data源(区)
      jValue: "", //Edit页面 站点地址 选项的值(街道)
      jLabel: "", //Edit页面 站点地址 选项的键名(街道)
      jJingwei: "", //Edit页面 站点地址 选项的经纬度(街道)
      jOption: [], //Edit页面 站点地址 Data源(街道)
      baiduMap: null,
      //
      searchData: {
        name: "",
        address: ""
        // state: '',
      },
      searchForm: [
        {
          type: "input",
          prop: "name",
          placeholder: "站点Name",
          width: 170
        },
        {
          type: "input",
          prop: "address",
          placeholder: "站点地址"
          // width: 150
        }
        // {
        //   type: 'select',
        //   prop: 'phone',
        //   placeholder: '站点所属',
        //   width: 150
        // }
      ],

      searchHandle: [
        {
          label: "Search",
          type: "success",
          icon: "el-icon-search",
          handle: e => this.init()
        }
      ],

      tableHandles: [
        {
          label: "Add站点",
          type: "primary",
          handle: e => {
            this.formData.id = null;
            this.isshowss = true;
            this.createdAcc();
          }
        }
      ],
      tableData: [],
      tableCols: [
        {
          label: "序号",
          prop: "id"
        },
        {
          label: "站点Name",
          prop: "name"
        },
        {
          label: "站点地址",
          prop: "address"
        },
        {
          label: "运营Type",
          prop: "state",
          formatter: e =>
            e.state == 1 ? "自营" : e.state == 2 ? "Operator" : "-"
        },
        // {
        //   label: '站点所属',
        //   prop: 'operatorName',
        //   isShow: () => {
        //     return sessionStorage.role == 'platform' ? true : false;
        //   }
        // },
        // {
        //   label: '设备Statistics',
        //   prop: 'mchNum'
        // },
        {
          label: "设备Statistics",
          prop: "mchNum"
        },
        {
          label: "Update Time",
          prop: "createdTime"
        },
        {
          label: "Operations",
          type: "button",
          width: 200,
          btnList: [
            {
              label: "Edit",
              type: "primary",
              handle: row => {
                this.isshowss = false;
                this.createdAcc(row);
              }
            },
            {
              label: "Delete",
              type: "primary",
              handle: row => this.del(row)
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        name: "",
        operatorId: "",
        agentId: "",
        state: "",
        address: "",
        lng: "",
        lat: ""
      },
      formCols: [
        {
          type: "input",
          label: "站点Name",
          placeholder: "Please Enter",
          width: 350,
          prop: "name"
        },
        // { type: "select", label: "选择Operator", placeholder: 'Please Enter', width: 350, prop: "operatorId", options: [] },
        // { type: "select", label: "选择Agent", placeholder: 'Please Enter', width: 350, prop: "agentId",options:[] },
        {
          type: "select",
          label: "运营Type",
          placeholder: "Please Enter",
          width: 350,
          prop: "state",
          options: [
            { label: "自营", value: 1 },
            { label: "Operator", value: 2 }
          ]
        }
        // { //只有Add才有，Edit没有
        //   type: "",
        //   isShow: () => {
        //     return !this.formData.id ? true : false;
        //   },
        // },
        // { type: "input", id: 'suggestId', label: "站点地址", width: 350, prop: "address" },
        // { type: "slot", name: 'slot3', label: '', prop: "lng" },
      ],
      formRules: {
        name: [{ required: true, message: "Please Enter", trigger: "blur" }],
        operatorId: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        agentId: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        state: [{ required: true, message: "Please Select", trigger: "blur" }],
        // lng: [
        //   { required: true, message: '请点击地图选择经纬度', trigger: 'blur' },
        // ],
        address: [
          { required: true, message: "Please Input详细地址", trigger: "blur" }
        ]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ]
    };
  },
  created() {},
  mounted() {
    this.init();
    this.get_operatorId();
  },
  methods: {
    async init() {
      this.tablePage.offset = this.tablePage.page;
      let param = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.site_list(param);
      if (res) {
        this.tableData = res.rows;
        this.tablePage.total = res.total;
      }
      // let resOpt = await this.api.getOperatorList({})
      // console.log("resOpt===", resOpt);

      // if (resOpt) {
      //   this.operatorId = resOpt.data.operatorId
      // }
      // Edit页面 站点地址  ---拿到省份(Data)
      const addressRes = await this.apis.allAddressList({});
      if (addressRes.code === 0) {
        var array = new Array();
        addressRes.result.forEach(item => {
          let obj = {
            label: item.name,
            value: item.adcode,
            jingwei: item.center
          };
          this.sOption.push(obj);
          array.push(obj);
        });

        // this.formCols[this.labIndex2(this.formCols, "address")].options = array;
      }
    },

    map() {
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder();
      map.addEventListener("click", function(e) {
        that.formData.lng = e.point.lng;
        that.formData.lat = e.point.lat;
        var pt = e.point;
        geoc.getLocation(pt, function(rs) {
          var addComp = rs.addressComponents;
          that.formData.city = addComp.city;
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
      });
      map.enableScrollWheelZoom(); //Enable滚轮放大缩小，默认Forbidden
      map.enableContinuousZoom(); //Enable地图惯性拖拽，默认Forbidden
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 10);
      });
    },
    createdAcc(row) {
      if (row) {
        this.formData.id = row.id;
      } else {
        this.formData.id = "";
      }
      this.elFormVisible().then(res => {
        if (row) {
          Object.keys(this.formData).forEach(key => {
            this.formData[key] = row[key];
          });
        }
      });
    },
    elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            let res = await this.apis.site_updata(this.formData);
            if (res) {
              this.init();
              this.elFormVisible();
            }
          } else {
            let res = await this.apis.site_save(this.formData);
            if (res) {
              this.init();
              this.elFormVisible();
            }
          }
        }
      });
    },

    async get_operatorId() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 100000
      });

      const list = res.rows || [];

      let options = [];
      list.map(res => {
        options.push({
          value: res.id,
          label: res.name
        });
      });

      // this.formCols[this.labIndex2(this.formCols, 'operatorId')].options = options;
    },

    del(row) {
      this.$confirm("确定要Delete吗？", "Hint", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning"
      })
        .then(async () => {
          var res = await this.apis.site_del({
            id: row.id
          });
          this.$message({
            type: "success",
            message: "DeleteSuccess!"
          });
          this.init();
        })
        .catch(() => {});
    },
    // // Edit页面 站点地址 的点击方法(省)
    sZhandiandizhi(value) {
      // console.log(value);
      let sObj = {};
      sObj = this.sOption.find(item => {
        //这里的sOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.sLabel = sObj.label; //拿到键名
      this.sOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.sJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData.lng = this.sJingwei.split(",")[0];
      this.formData.lat = this.sJingwei.split(",")[1];
      this.pt = this.sJingwei;
    },

    // // Edit页面 站点地址 的点击方法(市)
    cZhandiandizhi(value) {
      // console.log(value);
      let cObj = {};
      cObj = this.cOption.find(item => {
        //这里的cOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.cLabel = cObj.label; //拿到键名
      this.cOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.cJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData.lng = this.cJingwei.split(",")[0];
      this.formData.lat = this.cJingwei.split(",")[1];
      this.pt = this.cJingwei;
    },
    // // Edit页面 站点地址 的点击方法(区)
    qZhandiandizhi(value) {
      let qObj = {};
      qObj = this.qOption.find(item => {
        //这里的cOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.qLabel = qObj.label; //拿到键名
      this.qOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.qJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData.lng = this.qJingwei.split(",")[0];
      this.formData.lat = this.qJingwei.split(",")[1];
      this.pt = this.qJingwei;
    },

    // // Edit页面 站点地址 的点击方法(街道)
    jZhandiandizhi(value) {
      let jObj = {};
      jObj = this.jOption.find(item => {
        //这里的jOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.jLabel = jObj.label; //拿到键名
      console.log(this.jLabel);
      this.jOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.jJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData.lng = this.jJingwei.split(",")[0];
      this.formData.lat = this.jJingwei.split(",")[1];
      this.pt = this.jJingwei;
    },

    // // Edit页面地图 ---拿到城市（Data）
    czhandianfangfa(label, value) {
      this.cOption = []; //每次进来先清空城市的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            res.result.forEach(item => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              };
              this.cOption.push(obj);
            });
            console.log("市", this.cOption);
          }
        });
    },

    // // Edit页面地图 ---拿到区（Data）
    qzhandianfangfa(label, value) {
      this.qOption = []; //每次进来先清空区/县的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            res.result.forEach(item => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              };
              this.qOption.push(obj);
            });
            console.log("区", this.cOption);
          }
        });
    },
    // // Edit页面地图 ---拿到街道（Data）
    jzhandianfangfa(label, value) {
      this.jOption = []; //每次进来先清空街道的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            // 增加判断，如果镇下面没有街道，就直接让街道变成空
            if (res.result.length !== 0) {
              res.result.forEach(item => {
                let obj = {
                  label: item.name,
                  value: item.adcode,
                  jingwei: item.center
                };
                this.jOption.push(obj);
              });
            } else {
              this.jOption = [];
            }
            console.log("街", this.jOption);
          }
        });
    }
  },
  watch: {
    // 监听省，如果下拉框的省发生改变，就会发送请求，更新市的Data
    sLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用Edit页面 --站点地址-- 城市（Data） 的方法
        this.czhandianfangfa(this.sLabel, this.sValue);
        // 当重新选择省，市区街和站点地址情况，重新更新
        this.cLabel = "";
        this.qLabel = "";
        this.jLabel = "";
        this.cValue = "";
        this.qValue = "";
        this.jValue = "";
      }
    },
    // 监听市，如果下拉框的市发生改变，就会发送请求，更新区的Data
    cLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用Edit页面 --站点地址-- 区（Data） 的方法
        this.qzhandianfangfa(this.cLabel, this.cValue);
        // 当重新选择市，区街和站点地址情况，重新更新
        this.qLabel = "";
        this.jLabel = "";
        this.qValue = "";
        this.jValue = "";
      }
    },
    // 监听区，如果下拉框的区发生改变，就会发送请求，更新街道的Data
    qLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用Edit页面 --站点地址-- 街道（Data） 的方法
        this.jzhandianfangfa(this.qLabel, this.qValue);
        // 当重新选择区，街和站点地址情况，重新更新

        this.jLabel = "";
        this.jValue = "";
      }
    },
    // 监听街道，如果下拉框的街道发生改变，就会发送请求，更新街道的Data
    jValue(newV, oldV) {
      console.log(111111, newV, oldV);
      if (newV !== oldV) {
        // this.jLabel = ''
        // this.jValue = ''
        // 调用Edit页面 --站点地址-- 街道（Data） 的方法
        // this.jzhandianfangfa(this.qLabel, this.qValue)
      }
    },
    lng(newV, oldV) {
      if (newV !== oldV) {
        console.log(newV, oldV, "===============");
      }
    }
  },
  updated() {
    // 选择省市区街下拉框，Edit页面的站点地址会改变
    if (this.sLabel && !this.cLabel && !this.qLabel && !this.jLabel) {
      this.formData.address = "";
      this.formData.address = this.sLabel;
    } else if (this.sLabel && this.cLabel && !this.qLabel && !this.jLabel) {
      this.formData.address = "";
      this.formData.address = this.sLabel + this.cLabel;
    } else if (this.sLabel && this.cLabel && this.qLabel && !this.jLabel) {
      this.formData.address = "";
      this.formData.address = this.sLabel + this.cLabel + this.qLabel;
    } else if (this.sLabel && this.cLabel && this.qLabel && this.jLabel) {
      this.formData.address = "";
      this.formData.address =
        this.sLabel + this.cLabel + this.qLabel + this.jLabel;
    } else {
    }
  }
};
</script>

<style scoped lang="scss">
#l-map {
  height: 250px;
  width: 100%;
}

#r-result {
  width: 100%;
}

// ControlEdit页面 站点地址的长度
.szddz {
  width: 130px;
}

.czddz {
  width: 130px;
}

.qzddz {
  width: 130px;
}

.jzddz {
  width: 130px;
}

.zhandiandiz {
  position: relative;
  // top: -351px;
  top: -370px;
  left: 70px;
}

.zhandiandiz > span {
  margin-right: 10px;
}
</style>
